﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Xunit;
namespace OrderManagementSystem
{


    

    public class OrderServiceTests
    {
        // 测试添加订单功能
        [Fact]
        public void AddOrder_ShouldAddOrderCorrectly()
        {
            var service = new OrderService();
            var order = new Order { OrderId = 1, Customer = "Test" };

            service.AddOrder(order);

            var result = service.QueryByOrderId(1);
            Assert.Single(result); // 验证是否成功添加
        }

        // 测试删除订单功能
        [Fact]
        public void RemoveOrder_ShouldDeleteExistingOrder()
        {
            var service = new OrderService();
            service.AddOrder(new Order { OrderId = 1 });

            service.RemoveOrder(1);

            Assert.Empty(service.QueryByOrderId(1)); // 验证是否已删除
        }

        // 测试XML序列化功能
        [Fact]
        public void XmlExportImport_ShouldRoundTripCorrectly()
        {
            var service = new OrderService();
            service.AddOrder(new Order
            {
                OrderId = 1,
                Customer = "Test",
                Details = new List<OrderDetails> {
                new OrderDetails { ProductName = "Test", Price = 10, Quantity = 1 }
            }
            });

            string tempFile = Path.GetTempFileName();
            try
            {
                // 导出再导入测试
                service.ExportToXml(tempFile);
                var newService = new OrderService();
                newService.ImportFromXml(tempFile);

                var imported = newService.QueryByOrderId(1);
                Assert.Equal("Test", imported[0].Customer); // 验证数据一致性
            }
            finally
            {
                File.Delete(tempFile); // 清理临时文件
            }
        }

        // 测试查询功能
        [Fact]
        public void QueryByProduct_ShouldReturnCorrectOrders()
        {
            var service = new OrderService();
            service.AddOrder(new Order
            {
                OrderId = 1,
                Details = new List<OrderDetails> {
                new OrderDetails { ProductName = "Apple" }
            }
            });

            var results = service.QueryByProductName("Apple");
            Assert.Single(results); // 验证查询结果
        }
    }
    // 订单明细类
    public class OrderDetails
    {
        public string ProductName { get; set; } // 商品名称
        public int Quantity { get; set; }       // 商品数量
        public decimal Price { get; set; }      // 商品单价

        // 重写Equals方法，确保订单明细不重复
        public override bool Equals(object obj)
        {
            if (obj is OrderDetails other)
            {
                return ProductName == other.ProductName && Quantity == other.Quantity && Price == other.Price;
            }
            return false;
        }

        // 重写ToString方法，显示订单明细信息
        public override string ToString()
        {
            return $"商品名称: {ProductName}, 数量: {Quantity}, 单价: {Price:C}";
        }
    }

    // 订单类
    public class Order
    {
        public int OrderId { get; set; }                // 订单号
        public string Customer { get; set; }            // 客户
        public List<OrderDetails> Details { get; set; } // 订单明细列表
        public decimal TotalAmount => Details.Sum(d => d.Quantity * d.Price); // 订单总金额

        // 重写Equals方法，确保订单不重复
        public override bool Equals(object obj)
        {
            if (obj is Order other)
            {
                return OrderId == other.OrderId;
            }
            return false;
        }

        // 重写ToString方法，显示订单信息
        public override string ToString()
        {
            string details = string.Join("\n", Details.Select(d => d.ToString()));
            return $"订单号: {OrderId}, 客户: {Customer}, 总金额: {TotalAmount:C}\n订单明细:\n{details}";
        }
    }

    // 订单服务类
    public class OrderService
    {
        private List<Order> Orders { get; set; } = new List<Order>();

        // 添加订单
        public void AddOrder(Order order)
        {
            if (Orders.Contains(order))
            {
                throw new InvalidOperationException("订单已存在，无法重复添加！");
            }
            Orders.Add(order);
        }
        // 在OrderService类中添加以下方法
        public void ExportToXml(string filePath)
        {
            // 序列化订单列表到XML文件
            XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                serializer.Serialize(fs, Orders);
            }
        }

        public void ImportFromXml(string filePath)
        {
            // 从XML文件反序列化订单列表
            if (!File.Exists(filePath))
                throw new FileNotFoundException("XML file not found");

            XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                List<Order> importedOrders = (List<Order>)serializer.Deserialize(fs);
                Orders = importedOrders;
            }
        }
        // 删除订单
        public void RemoveOrder(int orderId)
        {
            var order = Orders.FirstOrDefault(o => o.OrderId == orderId);
            if (order == null)
            {
                throw new InvalidOperationException("订单不存在，无法删除！");
            }
            Orders.Remove(order);
        }

        // 修改订单
        public void ModifyOrder(Order order)
        {
            var existingOrder = Orders.FirstOrDefault(o => o.OrderId == order.OrderId);
            if (existingOrder == null)
            {
                throw new InvalidOperationException("订单不存在，无法修改！");
            }
            Orders.Remove(existingOrder);
            Orders.Add(order);
        }

        // 查询订单（按订单号）
        public List<Order> QueryByOrderId(int orderId)
        {
            return Orders.Where(o => o.OrderId == orderId).OrderBy(o => o.TotalAmount).ToList();
        }

        // 查询订单（按商品名称）
        public List<Order> QueryByProductName(string productName)
        {
            return Orders.Where(o => o.Details.Any(d => d.ProductName == productName))
                         .OrderBy(o => o.TotalAmount)
                         .ToList();
        }

        // 查询订单（按客户）
        public List<Order> QueryByCustomer(string customer)
        {
            return Orders.Where(o => o.Customer == customer)
                         .OrderBy(o => o.TotalAmount)
                         .ToList();
        }

        // 查询订单（按订单金额范围）
        public List<Order> QueryByAmountRange(decimal minAmount, decimal maxAmount)
        {
            return Orders.Where(o => o.TotalAmount >= minAmount && o.TotalAmount <= maxAmount)
                         .OrderBy(o => o.TotalAmount)
                         .ToList();
        }

        // 排序订单（默认按订单号排序）
        public void SortOrders()
        {
            Orders = Orders.OrderBy(o => o.OrderId).ToList();
        }

        // 排序订单（自定义排序）
        public void SortOrders(Func<Order, object> keySelector)
        {
            Orders = Orders.OrderBy(keySelector).ToList();
        }

        // 显示所有订单
        public void DisplayAllOrders()
        {
            foreach (var order in Orders)
            {
                Console.WriteLine(order);
                Console.WriteLine();
            }
        }
    }

    // 主程序
    class Program
    {
        static void Main(string[] args)
        {
            OrderService orderService = new OrderService();

            try
            {
                // 添加订单
                Order order1 = new Order
                {
                    OrderId = 1,
                    Customer = "张三",
                    Details = new List<OrderDetails>
                    {
                        new OrderDetails { ProductName = "手机", Quantity = 1, Price = 5000 },
                        new OrderDetails { ProductName = "耳机", Quantity = 2, Price = 200 }
                    }
                };
                orderService.AddOrder(order1);

                Order order2 = new Order
                {
                    OrderId = 2,
                    Customer = "李四",
                    Details = new List<OrderDetails>
                    {
                        new OrderDetails { ProductName = "笔记本", Quantity = 1, Price = 8000 },
                        new OrderDetails { ProductName = "鼠标", Quantity = 1, Price = 100 }
                    }
                };
                orderService.AddOrder(order2);

                // 显示所有订单
                Console.WriteLine("所有订单：");
                orderService.DisplayAllOrders();

                // 查询订单（按商品名称）
                Console.WriteLine("查询商品名称为'手机'的订单：");
                var result = orderService.QueryByProductName("手机");
                foreach (var order in result)
                {
                    Console.WriteLine(order);
                }

                // 修改订单
                order1.Details.Add(new OrderDetails { ProductName = "充电器", Quantity = 1, Price = 50 });
                orderService.ModifyOrder(order1);
                Console.WriteLine("修改后的订单1：");
                Console.WriteLine(order1);

                // 删除订单
                orderService.RemoveOrder(2);
                Console.WriteLine("删除订单2后的所有订单：");
                orderService.DisplayAllOrders();

                // 排序订单（按总金额）
                orderService.SortOrders(o => o.TotalAmount);
                Console.WriteLine("按总金额排序后的订单：");
                orderService.DisplayAllOrders();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }
    }
}